<?php

/**
 *
 * 系统控制器资源管理
 *
 * @author mmxie
 * @copyright Copyright (c) 2009 Green Shore (http://www.shumenol.com)
 * @version $Id: ResourceController.php 1059 2011-11-18 09:26:15Z mmxie $
 */
class System_ResourceController extends IG_Controller_Action
{
    /**
     * 资源列表
     * @author maomao.thx@gmail.com
     */
    public function listAction()
    {
        $roleId = $this->_getParam('role_id');

        $resource = new System_Model_Resource();
        $data = array();
        foreach ($resource->fetchAll() as $r) {
            $ctrl   = $r->getController();
            $action = $r->getAction();
            if (empty($data[$r->getModule()]['ctrls'][$ctrl])) {
                if (empty($data[$r->getModule()])) {
                    $data[$r->getModule()] = array(
                        'data'  => array(),
                        'ctrls' => array(),
                    );
                }
                if (!empty($ctrl)) {
                    $data[$r->getModule()]['ctrls'][$ctrl] = array(
                        'data'    => array(),
                        'actions' => array(),
                    );
                } else {
                    $data[$r->getModule()]['data'] = $r;
                    continue;
                }
            }

            if (empty($action)) {
                $data[$r->getModule()]['ctrls'][$ctrl]['data'] = $r;
            } else {
                $data[$r->getModule()]['ctrls'][$ctrl]['actions'][$action] = $r;
            }
        }


        $role = new System_Model_Role();
        $this->view->assign('resourceIds', $roleId ? $role->getResourceIds($roleId) : null);
        $this->view->assign('roleId', $roleId);
        $this->view->assign('roles', $role->fetchAll());

        $this->view->assign('data', $data);
        $this->view->headScript()->appendFile('/scripts/jquery/jquery.ig.dataManage.js');
        $this->view->headScript()->appendFile('/scripts/jquery/jquery.ig.btnAjax.js');
        $this->view->headScript()->appendFile('/scripts/jquery/jquery.treeTable.js');
        $this->view->headLink()->appendStylesheet('/style/jquery.treeTable.css');
    }

    /**
     * 资源初始化更新
     * @author maomao.thx@gmail.com
     */
    public function refreshAction()
    {
        $dirs = $this->getFrontController()->getControllerDirectory();

        foreach ($dirs as $module => $dir) {
            $key = "$module,,";

            $data[$key] = array(
                'module'   => $module,
            );

            foreach (glob($dir . '/*Controller.php') as $file) {
                $controller = $this->_rename(basename($file, "Controller.php"));
                $key = "$module,$controller,";
                include_once $file;
                $reflection = new Zend_Reflection_File($file);
                $reflectionClass = $reflection->getClass();

                $data[$key] = array(
                    'module'     => $module,
                    'controller' => $controller,
                );

                if ($reflectionClass->getDocComment()) {
                    $classDocblock = $reflectionClass->getDocblock();
                    $data[$key]['name']     = $classDocblock->getShortDescription();
                    if ($classDocblock->hasTag('author')) {
                        $data[$key]['employee'] = $classDocblock->getTag('author')->getDescription();
                    }
                }

                foreach (array_diff(
                        get_class_methods($reflectionClass->getName()),
                        get_class_methods('IG_Controller_Action')
                    ) as $method) {
                    if (substr($method, -6) == 'Action') {
                        $action = $this->_rename(substr($method, 0, -6));
                        $key = "$module,$controller,$action";
                        $data[$key] = array(
                            'module'     => $module,
                            'controller' => $controller,
                            'action'     => $action,
                        );

                        if ($reflectionClass->getMethod($method)->getDocComment()) {
                            $methodDocblock = $reflectionClass->getMethod($method)->getDocblock();
                            $data[$key]['name']     = $methodDocblock->getShortDescription();
                            if ($methodDocblock->hasTag('author')) {
                                $data[$key]['employee'] = $methodDocblock->getTag('author')->getDescription();
                            }
                        }
                    }
                }
            }
        }

        $resource = new System_Model_Resource();
        $diffKeys = $resource->fetchKey();

        $atime = date('Y-m-d H:i:s');
        $insertData = array_diff_key($data, $diffKeys);
        foreach ($insertData as $items) {
            $items += array(
                'resource_id' => null,
                'employee'    => 'system',
                'name'        => null,
                'module'      => null,
                'controller'  => null,
                'action'      => null,
                'atime'       => $atime
            );
            $resource->setOptions($items)->save(true);
        }

        $deleteData = array_diff_key($diffKeys, $data);
        foreach ($deleteData as $id) {
            $resource->setResourceId($id)->delete();
        }

        exit(json_encode(array(
            'statusCode' => 0,
            'message' => '增加了 ' . count($insertData) . ' 个方法, 删除了 ' . count($deleteData) . ' 个方法&nbsp;',
            'tip' => 1)));
    }

    /**
     * 资源信息修改
     * @author maomao.thx@gmail.com
     */
    public function saveAction()
    {
        $params = $this->_getParams(array('resource_id', 'employee', 'name', 'param'));
        $resource = new System_Model_Resource($params);
        $resource->save(true);
        if ($params['param']) {
            Zend_Registry::get('lvan_cache')->remove('IG_Acl');
        }
        exit(json_encode(array('statusCode' => 0)));
    }

    /**
     * 资源权限分配
     * @author maomao.thx@gmail.com
     */
    public function assignAction()
    {
        $resourceId = $this->_getParam('resource_id');
        $roleId = $this->_getParam('role_id');

        $role = new System_Model_Role();
        $role->setRoleId($roleId)->saveResource($resourceId);

        Zend_Registry::get('lvan_cache')->remove('IG_Acl');

        exit(json_encode(array('statusCode' => 0, 'tip' => 1)));
    }

    protected function _rename($name)
    {
        $replace = array('-a', '-b', '-c', '-d', '-e', '-f', '-g', '-h', '-i',
                         '-j', '-k', '-l', '-m', '-n', '-o', '-p', '-q', '-r',
                         '-s', '-t', '-u', '-v', '-w', '-x', '-y', '-z', );
        $search = range('A', 'Z');
        return ltrim(str_replace($search, $replace, $name), '-');
    }
}